module apb_reg #(
  parameter REG_ADDR = 24'b000000   // Mapped address
)(
  input  wire                 pclk,                   // APB bus clock.
  input  wire                 presetn,                // APB reset
  input  wire                 psel,                   // APB peripheral select.
  input  wire                 penable,                // APB enable signal, indicates ACCESS phase.
  input  wire                 pwrite,                 // APB write enable, 1 = write.
  input  wire [31:0]          paddr,                  // APB address bus.
  input  wire [31:0]          pwdata,                 // APB write data bus.
  output reg  [31:0]          prdata,                 // APB read data bus.
  output reg                  pready,                 // APB ready signal, indicates transaction complete.

  input                       ext_inc_en,             // Enable external auto-increment.
  input                       ext_inc_pulse           // Pulse signal triggers +1 increment.
);

reg [31:0] reg_out;

// Write operation: update the external register in ACCESS phase
always @(posedge pclk or negedge presetn) begin
  if (~presetn) begin
    reg_out <= 32'b0;        // Reset to zero
  end
  else begin
    // APB write.
    if (psel && (paddr[23:0] == REG_ADDR)) begin
      if(~penable) begin
        pready <= 1'b0;
      end
      else begin
        pready = 1'b1;
        if(pwrite)
          reg_out <= pwdata;
      end
    end
    // External auto-increment.
    else if (ext_inc_en && ext_inc_pulse) begin
      reg_out <= reg_out + 1'b1;
      pready  <= 1'b1;
    end
    // Idle.
    else begin
      pready <= 1'b1;
    end
  end
end

// APB read.
always @(*) begin
  prdata = reg_out;
end

endmodule